import numpy as np


class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        # 初始化权重和偏置
        self.W1 = np.random.randn(self.input_size, self.hidden_size)
        self.b1 = np.zeros((1, self.hidden_size))
        self.W2 = np.random.randn(self.hidden_size, self.output_size)
        self.b2 = np.zeros((1, self.output_size))

    def forward(self, X):
        # 前向传播
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = np.tanh(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        self.a2 = self.sigmoid(self.z2)

        return self.a2

    def backward(self, X, y, learning_rate):
        m = X.shape[0]

        # 计算输出层的误差
        dZ2 = self.a2 - y
        dW2 = (1 / m) * np.dot(self.a1.T, dZ2)
        db2 = (1 / m) * np.sum(dZ2, axis=0, keepdims=True)

        # 计算隐藏层的误差
        dZ1 = np.dot(dZ2, self.W2.T) * (1 - np.power(self.a1, 2))
        dW1 = (1 / m) * np.dot(X.T, dZ1)
        db1 = (1 / m) * np.sum(dZ1, axis=0)

        # 更新权重和偏置
        self.W2 -= learning_rate * dW2
        self.b2 -= learning_rate * db2
        self.W1 -= learning_rate * dW1
        self.b1 -= learning_rate * db1

    def train(self, X, y, epochs, learning_rate):
        for epoch in range(epochs):
            # 前向传播
            output = self.forward(X)

            # 反向传播
            self.backward(X, y, learning_rate)

            # 计算损失
            loss = self.calculate_loss(y, output)

            # 每1000个epoch打印一次损失
            if epoch % 1000 == 0:
                print(f"Epoch {epoch}: Loss = {loss}")

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def calculate_loss(self, y_true, y_pred):
        m = y_true.shape[0]
        loss = -1 / m * np.sum(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))
        return loss


# 创建神经网络对象
input_size = 10
hidden_size = 15
output_size = 5
nn = NeuralNetwork(input_size, hidden_size, output_size)

# 准备训练数据
X = np.random.randn(100, input_size)
y = np.random.randint(0, 2, size=(100, output_size))

# 训练神经网络
epochs = 10000
learning_rate = 0.1
nn.train(X, y, epochs, learning_rate)

# 使用训练好的模型进行预测
input_data = np.random.randn(1, input_size)
output = nn.forward(input_data)
print("预测结果：", output)